<template>
  <div class="transaction-container">
    <el-card class="transaction-card">
      <template #header>
        <div class="card-header">
          <div class="header-text">
            <h3>交易记录管理</h3>
            <p>查看和管理平台交易记录</p>
          </div>
          <div class="header-actions">
            <el-input
                v-model="searchForm.visitorName"
                placeholder="游客姓名"
                style="width: 150px; margin-right: 10px;"
                clearable
            />
            <el-input
                v-model="searchForm.guideName"
                placeholder="地陪姓名"
                style="width: 150px; margin-right: 10px;"
                clearable
            />
            <el-button type="primary" @click="handleSearch" round>
              <i class="el-icon-search"></i> 查询
            </el-button>
            <el-button @click="handleReset" round>
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="transactions" style="width: 100%" border>
        <el-table-column prop="transactionId" label="交易编号" width="200"/>
        <el-table-column prop="visitorName" label="游客姓名" width="200"/>
        <el-table-column prop="guideName" label="地陪姓名" width="200"/>
        <el-table-column prop="visitorPayment" label="游客付款(元)" width="240"/>
        <el-table-column prop="guideSalary" label="地陪收款(元)" width="240"/>
        <el-table-column prop="date" label="交易时间" width="250">
          <template #default="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
                round
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="page.currentPage"
            v-model:page-size="page.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="page.totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </el-card>

    <!-- 整合后的图表卡片 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <div class="header-text">
            <h3>数据分析图表</h3>
            <p>查看平台运营数据</p>
          </div>
          <div class="header-actions">
            <!-- 图表切换按钮组 -->
            <el-radio-group v-model="activeChart" @change="handleChartChange" size="small">
              <el-radio-button label="trend">交易趋势</el-radio-button>
              <el-radio-button label="rank">地陪收入排行</el-radio-button>
              <el-radio-button label="distribution">游客消费分布</el-radio-button>
            </el-radio-group>
            <el-button @click="refreshActiveChart()" size="small" type="primary" round style="margin-left: 10px;">
              <i class="el-icon-refresh"></i> 刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <div class="chart-container">
        <!-- 交易趋势图 -->
        <div v-if="activeChart === 'trend'" class="chart-wrapper">
          <div ref="trendChart" class="echarts-container"></div>
          <div v-if="loadingTrend" class="loading-overlay">
            <el-skeleton :rows="6" animated />
          </div>
          <div v-if="!loadingTrend && trendData.length === 0" class="no-data">
            暂无交易趋势数据
          </div>
        </div>

        <!-- 地陪收入排行 -->
        <div v-if="activeChart === 'rank'" class="chart-wrapper">
          <div ref="rankChart" class="echarts-container"></div>
          <div v-if="loadingRank" class="loading-overlay">
            <el-skeleton :rows="6" animated />
          </div>
          <div v-if="!loadingRank && guideRankData.length === 0" class="no-data">
            暂无地陪收入数据
          </div>
        </div>

        <!-- 游客消费分布 -->
        <div v-if="activeChart === 'distribution'" class="chart-wrapper">
          <div ref="distributionChart" class="echarts-container"></div>
          <div v-if="loadingDistribution" class="loading-overlay">
            <el-skeleton :rows="6" animated />
          </div>
          <div v-if="!loadingDistribution && visitorDistributionData.length === 0" class="no-data">
            暂无游客消费分布数据
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import m_transaction_api from "@/api/manager/m_transaction_api.js";
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'

// 分页数据
const page = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0
})

// 搜索表单
const searchForm = ref({
  visitorName: '',
  guideName: ''
})

// 交易记录数据
const transactions = ref([])

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.getFullYear() + '-' +
      String(date.getMonth() + 1).padStart(2, '0') + '-' +
      String(date.getDate()).padStart(2, '0') + ' ' +
      String(date.getHours()).padStart(2, '0') + ':' +
      String(date.getMinutes()).padStart(2, '0') + ':' +
      String(date.getSeconds()).padStart(2, '0')
}

// 加载交易记录
const loadTransactions = async () => {
  try {
    const params = {
      currentPage: page.value.currentPage,
      pageSize: page.value.pageSize,
      visitorName: searchForm.value.visitorName,
      guideName: searchForm.value.guideName
    }

    const result = await m_transaction_api.page(params)

    if (result && result.data) {
      page.value.totalCount = result.totalCount || 0

      let transactionData = []
      if (Array.isArray(result.data)) {
        transactionData = result.data
      } else if (result.data.data && Array.isArray(result.data.data)) {
        transactionData = result.data.data
        page.value.totalCount = result.data.totalCount || result.totalCount || transactionData.length
      } else {
        transactionData = []
        page.value.totalCount = 0
      }

      // 为每条记录添加伪装的交易编号
      transactions.value = transactionData.map(item => {
        return {
          ...item,
          transactionId: `TX${String(item.id).padStart(8, '0')}` // 生成伪装的交易编号
        }
      })
    }
  } catch (error) {
    console.error('加载交易记录失败:', error)
    ElMessage.error('加载交易记录失败: ' + error.message)
  }
}

// 查询功能
const handleSearch = async () => {
  page.value.currentPage = 1
  await loadTransactions()
}

// 重置查询条件
const handleReset = async () => {
  searchForm.value = {
    visitorName: '',
    guideName: ''
  }
  page.value.currentPage = 1
  await loadTransactions()
}

// 分页功能
const handleSizeChange = async (val) => {
  page.value.pageSize = val
  page.value.currentPage = 1
  await loadTransactions()
}

const handleCurrentChange = async (val) => {
  page.value.currentPage = val
  await loadTransactions()
}

// 删除交易记录
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除交易记录(交易编号: ${row.transactionId})吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const response = await m_transaction_api.delete(row.id)
      if (response && (typeof response === 'string' || response.code === 200)) {
        ElMessage.success('删除成功')
        await loadTransactions()
      } else {
        if (response && (typeof response === 'number' && response > 0)) {
          ElMessage.success('删除成功')
          await loadTransactions()
        } else {
          throw new Error(response?.msg || '删除失败')
        }
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 图表相关 - 切换状态管理
const activeChart = ref('trend') // 默认显示交易趋势图

// 交易趋势
const trendChart = ref(null)
const trendChartInstance = ref(null)
const trendData = ref([])
const loadingTrend = ref(false)

// 地陪收入排行
const rankChart = ref(null)
const rankChartInstance = ref(null)
const guideRankData = ref([])
const loadingRank = ref(false)

// 游客消费分布
const distributionChart = ref(null)
const distributionChartInstance = ref(null)
const visitorDistributionData = ref([])
const loadingDistribution = ref(false)

// 切换图表时的处理函数
const handleChartChange = async (chartType) => {
  // 根据选择的图表类型加载对应数据
  switch(chartType) {
    case 'trend':
      if (trendData.value.length === 0) await loadTrendData();
      break;
    case 'rank':
      if (guideRankData.value.length === 0) await loadGuideRankData();
      break;
    case 'distribution':
      if (visitorDistributionData.value.length === 0) await loadVisitorDistributionData();
      break;
  }
}

// 刷新当前激活的图表数据
const refreshActiveChart = async () => {
  switch(activeChart.value) {
    case 'trend':
      await loadTrendData();
      break;
    case 'rank':
      await loadGuideRankData();
      break;
    case 'distribution':
      await loadVisitorDistributionData();
      break;
  }
}

// 加载趋势数据
const loadTrendData = async () => {
  loadingTrend.value = true
  try {
    const response = await m_transaction_api.getTrendData({ days: 7 })
    console.log('趋势数据原始响应:', response)

    if (Array.isArray(response)) {
      trendData.value = [...response].sort((a, b) =>
          new Date(a.date) - new Date(b.date)
      )
      await nextTick()
      renderTrendChart()

      if (response.length === 0) {
        ElMessage.info('当前时间段内暂无交易数据')
      }
    } else {
      trendData.value = []
      ElMessage.warning('获取趋势数据格式不正确')
    }
  } catch (error) {
    console.error('加载趋势数据失败:', error)
    ElMessage.error('加载趋势数据失败: ' + (error.message || '未知错误'))
    trendData.value = []
  } finally {
    loadingTrend.value = false
  }
}

// 加载地陪收入排行
const loadGuideRankData = async () => {
  loadingRank.value = true
  try {
    const response = await m_transaction_api.getGuideRankData()
    console.log('地陪收入排行原始响应:', response)

    if (Array.isArray(response)) {
      guideRankData.value = [...response].sort((a, b) => b.totalSalary - a.totalSalary)
      await nextTick()
      renderRankChart()

      if (response.length === 0) {
        ElMessage.info('当前暂无地陪收入数据')
      }
    } else {
      guideRankData.value = []
      ElMessage.warning('获取地陪收入数据格式不正确')
    }
  } catch (error) {
    console.error('加载地陪收入排行失败:', error)
    ElMessage.error('加载地陪收入排行失败: ' + (error.message || '未知错误'))
    guideRankData.value = []
  } finally {
    loadingRank.value = false
  }
}

// 加载游客消费分布
const loadVisitorDistributionData = async () => {
  loadingDistribution.value = true
  try {
    const response = await m_transaction_api.getVisitorDistributionData()
    console.log('游客消费分布原始响应:', response)

    if (Array.isArray(response)) {
      visitorDistributionData.value = response
      await nextTick()
      renderDistributionChart()

      if (response.length === 0) {
        ElMessage.info('当前暂无游客消费分布数据')
      }
    } else {
      visitorDistributionData.value = []
      ElMessage.warning('获取游客消费分布数据格式不正确')
    }
  } catch (error) {
    console.error('加载游客消费分布失败:', error)
    ElMessage.error('加载游客消费分布失败: ' + (error.message || '未知错误'))
    visitorDistributionData.value = []
  } finally {
    loadingDistribution.value = false
  }
}

// 渲染交易趋势图
const renderTrendChart = () => {
  if (!trendChart.value || !trendData.value.length) return

  if (trendChartInstance.value) {
    trendChartInstance.value.dispose()
  }

  trendChartInstance.value = echarts.init(trendChart.value)
  // 1. 定义完整的日期范围（例如，最近7天）
  const today = new Date();
  const dates = [];
  //获取当前日期
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    //格式化日期
    const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    //添加到日期列表
    dates.push(formattedDate);
  }

  // 2. 创建一个映射，用于快速查找每个日期对应的数据
  const dataMap = new Map();
  trendData.value.forEach(item => {
    dataMap.set(item.date, item);
  });

  // 3. 根据完整的日期列表构建 series 数据
  const payments = [];
  const salaries = [];
  dates.forEach(date => {
    const data = dataMap.get(date);
    if (data) {
      payments.push(data.totalPayment || 0);
      salaries.push(data.totalSalary || 0);
    } else {
      // 如果某天没有数据，使用null来表示空值
      payments.push(null);
      salaries.push(null);
    }
  });

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderColor: '#ccc',
      textStyle: { color: '#333' },
      formatter: (params) => {
        const date = params[0].axisValue;
        let payment = params[0].value === null ? '无数据' : `￥${params[0].value}`;
        let salary = params[1].value === null ? '无数据' : `￥${params[1].value}`;
        return `${date}<br/>游客付款: ${payment}<br/>地陪收款: ${salary}`;
      }
    },
    legend: { data: ['游客付款总额', '地陪收款总额'], top: 'bottom' },
    grid: { left: '10%', right: '8%', bottom: '15%', containLabel: true },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: {
      type: 'value',
      name: '金额（元）',
      splitLine: { lineStyle: { type: 'dashed' } }
    },
    series: [
      {
        name: '游客付款总额',
        type: 'line',
        data: payments,
        smooth: true,
        itemStyle: {color: '#409EFF'},
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [{offset: 0, color: 'rgba(64, 158, 255, 0.3)'}, {offset: 1, color: 'rgba(64, 158, 255, 0)'}]
          }
        },
        // 设置线段样式，使空值处的线段为虚线
        lineStyle: {
          type: 'solid'
        },
        // 设置折线图的连接方式，允许连接空值
        connectNulls: true
      },
      {
        name: '地陪收款总额',
        type: 'line',
        data: salaries,
        smooth: true,
        itemStyle: {color: '#67C23A'},
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [{offset: 0, color: 'rgba(103, 194, 58, 0.3)'}, {offset: 1, color: 'rgba(103, 194, 58, 0)'}]
          }
        },
        lineStyle: {
          type: 'solid'
        },
        connectNulls: true
      }
    ],
    dataZoom: [{
      type: 'slider',
      start: 0,
      end: 100,
      height: 12,
      bottom: 20,
      backgroundColor: '#f5f7fa',
      fillerColor: 'rgba(64, 158, 255, 0.1)',
      borderColor: '#dcdfe6'
    }]
  }

  trendChartInstance.value.setOption(option)
}


// 渲染地陪收入排行
const renderRankChart = () => {
  if (!rankChart.value || !guideRankData.value.length) return

  if (rankChartInstance.value) {
    rankChartInstance.value.dispose()
  }

  rankChartInstance.value = echarts.init(rankChart.value)
  const names = guideRankData.value.map(item => item.guideName)
  const salaries = guideRankData.value.map(item => item.totalSalary || 0)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {type: 'shadow'},
      formatter: '{b}: ￥{c}'
    },
    grid: {left: '3%', right: '4%', bottom: '3%', containLabel: true},
    xAxis: {type: 'value', name: '收入（元）'},
    yAxis: {
      type: 'category',
      data: names,
      axisLabel: {interval: 0},
      inverse: true
    },
    series: [{
      name: '地陪收入',
      type: 'bar',
      data: salaries,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          {offset: 0, color: '#409EFF'},
          {offset: 1, color: '#67C23A'}
        ])
      },
      label: {
        show: true,
        position: 'right',
        formatter: '￥{c}'
      }
    }]
  }

  rankChartInstance.value.setOption(option)
}

// 渲染游客消费分布
const renderDistributionChart = () => {
  if (!distributionChart.value || !visitorDistributionData.value.length) return

  if (distributionChartInstance.value) {
    distributionChartInstance.value.dispose()
  }

  distributionChartInstance.value = echarts.init(distributionChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}人 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: visitorDistributionData.value.map(item => item.paymentRange)
    },
    series: [{
      name: '消费人数',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {show: false, position: 'center'},
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {show: false},
      data: visitorDistributionData.value.map(item => ({
        name: item.paymentRange,
        value: item.count
      }))
    }]
  }

  distributionChartInstance.value.setOption(option)
}

// 窗口大小变化处理
const handleResize = () => {
  // 只重新渲染当前激活的图表
  if (activeChart.value === 'trend') {
    trendChartInstance.value?.resize()
  } else if (activeChart.value === 'rank') {
    rankChartInstance.value?.resize()
  } else if (activeChart.value === 'distribution') {
    distributionChartInstance.value?.resize()
  }
}

// 监听图表切换，重新渲染
watch(activeChart, (newVal) => {
  nextTick(() => {
    if (newVal === 'trend' && trendData.value.length > 0) {
      renderTrendChart()
    } else if (newVal === 'rank' && guideRankData.value.length > 0) {
      renderRankChart()
    } else if (newVal === 'distribution' && visitorDistributionData.value.length > 0) {
      renderDistributionChart()
    }
  })
})

// 生命周期钩子
onMounted(async () => {
  await loadTransactions()
  await loadTrendData() // 默认加载趋势图数据
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  trendChartInstance.value?.dispose()
  rankChartInstance.value?.dispose()
  distributionChartInstance.value?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.transaction-container {
  padding: 20px;
}

.transaction-card, .chart-card {
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(168, 192, 235, 0.2);
  margin-bottom: 20px;
  border: none;
}

:deep(.transaction-card .el-card__header),
:deep(.chart-card .el-card__header) {
  background: linear-gradient(135deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #409eff;
  border-radius: 15px 15px 0 0 !important;
  padding: 25px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.header-text h3 {
  margin: 0 0 5px 0;
  font-size: 22px;
  font-weight: 600;
  color: #409eff;
}

.header-text p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
}

/* 图表样式 */
.chart-container {
  position: relative;
  width: 100%;
  padding: 20px 0;
}

.chart-wrapper {
  width: 100%;
  position: relative;
}

.echarts-container {
  width: 100%;
  height: 500px;
  margin: 0;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border-radius: 10px;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 16px;
  text-align: center;
}

@media (max-width: 768px) {
  .transaction-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
    margin-top: 15px;
  }

  .echarts-container {
    height: 350px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-table th) {
    font-size: 12px;
    padding: 8px 0;
  }
}
</style>
